const express=require("express");
const router=express.Router();
const multer = require('multer');  
const db=require("../db.js");
const tr = require('../tokenRule.js')
// 查询所有
router.get("/selectAll",tr.verifyToken,(req,res)=>{
	let sql="select id,username,age,phone,idcard,sex,address from user";
	db.query(sql,(err,data)=>{
		if(err){
			res.send({msg:err.message});
			return;
		}else{
			res.send({
				msg:"请求成功",
				data:data,
				code:200,
			})
		}
	})
})
// 删除
router.post("/delUser",tr.verifyToken,(req,res)=>{
	let sql="delete from user where id=?";
	db.query(sql,req.body.id,(err,data)=>{
		if(err){
			res.send({msg:err.message});
			return;
		}else{
			res.send({
				msg:"删除成功",
				data:null,
				code:200,
			})
		}
	})
})
// 编辑
router.post("/updTest",tr.verifyToken,(req,res)=>{
	let sql="update user set username=?,sex=?,age=?,address=?,phone=? where id=?";
	let sj=[req.body.username,req.body.sex,req.body.age,req.body.address,req.body.phone,req.body.id]
	db.query(sql,sj,(err,data)=>{
		if(err){
			res.send({msg:err.message});
			return;
		}else{
			res.send({
				msg:"修改成功",
				data:null,
				code:200,
			})
		}
	})
})
// 注册
router.post("/register",(req,res)=>{
	let { username, password } = req.body
	  // 1.构造SQL语句。
	const sql = `select * from user where username= '${username}'`
	db.query(sql,(err,data)=>{
		if(err){
			res.send({msg:err.message});
			return;
		}else{
			if(data.length==1){ //如果查询出是2，仍然登录失败
				res.send({
				  code: 500,
				  msg: '用户名重复，请重新输入新的用户名',
				});
			}else{
				let sqls="insert into user(username,password) values(?,?)";
				let objs=[username,password]
				db.query(sqls,objs,(err,dataAdd)=>{
					if(err){
						res.send({msg:err.message});
						return;
					}else{
						res.send({
							msg:"success",
							data:dataAdd,
							code:200,
						})
					}
				})
			}
		}
	})
})
// 登录
router.post("/login",(req,res)=>{
	let { username, password } = req.body
	  // 1.构造SQL语句。
	const sql = `select * from user where username= '${username}' and password='${password}'`
	db.query(sql,(err,data)=>{
		if (err) {
		  throw err
		} else {
		  if (!data.length) {
			res.send({
			  code: 500,
			  msg:'请检查用户名或者密码'
			});
		  } else if(data.length==1){ //如果查询出是2，仍然登录失败
			const token=tr.generateToken(username);
			res.send({
			  code: 200,
			  msg: '恭喜你登录成功',
			  token:token
			});
		  } else {
			res.send({
			  code: 500,
			  msg:'请检查用户名或者密码'
			});
		  }
		}
	})
})

  
const storage = multer.diskStorage({  
  destination: (req, file, cb) => {  
    cb(null, '../uploads');  
  },  
  filename: (req, file, cb) => {  
    const extension = file.originalname.split('.').pop();  
    cb(null, `${Date.now()}.${extension}`);  
  }  
});  
  
const upload = multer({ storage: storage });
router.post('/upload', upload.single('file'),tr.verifyToken, (req, res) => {  
  console.log(req.body.file.name)
  const imageUrl = `uploads/${req.body.file.name}`;  
  res.json({ imageUrl });  
});
module.exports=router